import type { ContextMenuItem } from "./types";
import { h, computed, toRefs, nextTick, ref, reactive } from "vue";
import { ElButton } from "element-plus";
import { ComponentHelper } from "../Helper/ComponentHelper";

export const showContextMenu = (
  popupPosition: { x: number; y: number },
  menu: ContextMenuItem[],
  onSelect?: (id: number | undefined) => void
) => {
  const showMenu = ref(false);
  // 解构菜单坐标并且创建响应式变量
  const { x, y } = toRefs(reactive(popupPosition));
  // 分隔符样式
  const separatorStyle = {
    margin: "2px 6px",
    borderTop: "1px solid rgba(200, 200, 200, 0.8)",
    padding: 0,
  };
  // 菜单项样式
  const menuItemStyle = (item: (typeof menu)[number]) => ({
    height: "32px",
    minWidth: "128px",
    border: 0,
    margin: 0,
    padding: item.icon ? "0 10px" : "0 30px",
    justifyContent: "left",
  });

  // 菜单视图样式
  const menuStyle = computed(() => ({
    position: "absolute",
    top: `${showMenu.value ? y.value : 0}px`,
    left: `${showMenu.value ? x.value : 0}px`,
    zIndex: 9999,
    background: "#fff",
    boxShadow: "0 0 5px rgba(0,0,0,0.2)",
    borderRadius: "5px",
    display: "flex",
    flexDirection: "column",
    maxHeight: "60vh",
    overflowY: "auto",
    visibility: showMenu.value ? "visible" : "hidden",
  }));

  // 菜单项被点击
  const onMenuClick = (item: (typeof menu)[number]) => {
    // 关闭菜单
    destroyMenu();
    // 触发选择事件
    onSelect?.(item?.id);
  };

  // 监听鼠标事件
  const listenerMouseEvent = () => {
    // 鼠标点击事件监听器，用于判断点击是否在 ContextMenu 内部
    document.addEventListener("click", handleClickOutside, true);
    // 鼠标右键事件监听器，用于判断点击是否在 ContextMenu 内部
    document.addEventListener("contextmenu", handleClickOutside, true);
  };
  // 移除鼠标事件
  const removelistenerMouseEvent = () => {
    document.removeEventListener("click", handleClickOutside, true);
    document.removeEventListener("contextmenu", handleClickOutside, true);
  };
  // 处理鼠标事件
  const handleClickOutside = (e: MouseEvent) => {
    if (!(e.target instanceof Element)) return;
    if (!div.contains(e.target)) {
      destroyMenu();
    }
  };

  // 销毁菜单
  const destroyMenu = () => {
    // 移除鼠标事件监听器
    removelistenerMouseEvent();
    // 卸载菜单
    ContextMenu.unmount();
  };

  // 创建菜单项
  const menuItem = menu.map((item) => {
    if (item.label === "-") {
      return h("div", { style: separatorStyle });
    } else {
      return h(
        ElButton,
        {
          icon: item.icon,
          disabled: item.disabled,
          style: menuItemStyle(item),
          onClick: () => onMenuClick(item),
        },
        () => item.label
      );
    }
  });
  // 创建菜单虚拟节点
  const contextMenu = () => h("div", { style: menuStyle.value }, menuItem);

  const ContextMenu = ComponentHelper.mount(contextMenu);
  const div = ContextMenu.getContainer();

  // 监听鼠标事件
  listenerMouseEvent();

  nextTick(() => {
    // 获取当前窗口的宽度
    const viewWidth = window.innerWidth;
    const viewHeight = window.innerHeight;

    // 获取 ContextMenu 的 DOM 元素
    const menuDiv = div.children[0] as HTMLDivElement;
    const width = menuDiv.offsetWidth;
    const height = menuDiv.offsetHeight;

    // 重新计算弹出位置防止超出屏幕
    x.value = x.value + width > viewWidth ? x.value - width : x.value;
    y.value = y.value + height > viewHeight ? y.value - height : y.value;

    // 显示菜单
    showMenu.value = true;
  });
};
